import LogFactory from "log/LogFactory";

const log = LogFactory.getLog("DataStorage") ;
export default class DataStorage<T extends object> {

    private isWrite: boolean = false ;
    /**
     * 如果为true表示已经从本地读取过数据
     */
    private isReadLocal: boolean = false ;
    private cache: T | null = null ;
    public saveData(key: string,data: T): void {
        this.isWrite = true ;
        if (!data){
            log.debug("数据为空，不保存") ;
            return ;
        }
        this.cache = data ;
        window.localStorage.setItem(key,JSON.stringify(data)) ;
    }
    public findData(key: string): T | null {
        if (this.isWrite){
            this.isWrite = false ;
           let data = this.findLocalData(key) ;
           this.cache = data ;
           return data ;
        }
        if(this.isReadLocal){
            return this.cache as T ;
        }
        // 从本地查找数据
        let data = this.findLocalData(key) ;
        this.cache = data ;
        this.isReadLocal = true ;
        return data ;
    }

    private findLocalData(key: string): T | null {
        log.info("从本地localStorage查找数据",key) ;
        let data = window.localStorage.getItem(key) ;
        if (!data){
            log.debug("找不到数据",key) ;
            return null ;
        }
        return JSON.parse(data) ;
    }

}